import { isSymbol, isNaN } from './type'

export const toInt = <T extends number | null = number>(
    value: any,
    defaultValue?: T
): number | T => {
    const def = defaultValue === undefined ? 0 : defaultValue
    if (value === null || value === undefined) {
        return def
    }
    const result = parseInt(value, 10)
    return isNaN(result) ? def : result
}

export function toNumber(value?: unknown, defaultValue?: number): number {
    const def = defaultValue === undefined ? 0 : defaultValue
    if (isSymbol(value)) {
        return def
    }
    const num = Number(value)
    return isNaN(num) ? def : num
}

export const toFloat = <T extends number | null = number>(
    value: any,
    defaultValue?: T
): number | T => {
    const def = defaultValue === undefined ? 0.0 : defaultValue
    if (value === null || value === undefined) {
        return def
    }
    const result = parseFloat(value)
    return isNaN(result) ? def : result
}
